from datetime import datetime, timedelta

from fastapi import APIRouter, Depends, Request, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession

from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.service.login_service import LoginService
from module_stock.entity.vo.settlement_vo import SettlementPageQueryModel, DeleteSettlementModel, GenerateStatModel
from module_stock.service.settlement_service import SettlementService
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil

settlementController = APIRouter(prefix='/stock/settlement', dependencies=[Depends(LoginService.get_current_user)])


@settlementController.get(
    '/list', response_model=PageResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('stock:settlement:list'))]
)
async def get_stock_settlement_list(
        request: Request,
        settlement_page_query: SettlementPageQueryModel = Depends(SettlementPageQueryModel.as_query),
        query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    settlement_page_query_result = await SettlementService.get_settlement_list_services(query_db, settlement_page_query,
                                                                                        is_page=True)
    logger.info('获取成功')

    return ResponseUtil.success(model_content=settlement_page_query_result)


@settlementController.delete('/{ids}', dependencies=[Depends(CheckUserInterfaceAuth('stock:settlement:remove'))])
@Log(title='交易交割记录', business_type=BusinessType.DELETE)
async def delete_stock_settlement(request: Request, ids: str, query_db: AsyncSession = Depends(get_db)):
    delete_settlement = DeleteSettlementModel(ids=ids)
    delete_settlement_result = await SettlementService.delete_settlement_services(query_db, delete_settlement)
    logger.info(delete_settlement_result.message)

    return ResponseUtil.success(msg=delete_settlement_result.message)


@settlementController.post('/importData', dependencies=[Depends(CheckUserInterfaceAuth('stock:settlement:edit'))])
async def batch_import_settlement(
        request: Request,
        file: UploadFile = File(...),
        query_db: AsyncSession = Depends(get_db),
):
    batch_import_result = await SettlementService.batch_import_settlement_services(
        query_db, file
    )
    logger.info(batch_import_result.message)

    return ResponseUtil.success(msg=batch_import_result.message)


@settlementController.post('/generate', dependencies=[Depends(CheckUserInterfaceAuth('stock:settlement:edit'))])
@Log(title='股票统计', business_type=BusinessType.UPDATE)
async def generate_stat_stock(
        request: Request,
        generate_stat: GenerateStatModel,
        query_db: AsyncSession = Depends(get_db),
):
    """
    根据结算数据生成股票统计数据，目前支持清仓股票统计和历史持仓统计
    历史持仓统计需要起初始日期start_date=2024-10-01开始统计
    清仓统计只需要统计当天即可，当前没用到历史持仓，所以默认统计当天
    :param request: 请求对象
    :param generate_stat: 参数
    :param query_db: 数据库会话
    :return: 生成结果
    """
    logger.info(f'开始股票统计')
    # 如果没有提供具体日期，只统计今天
    if not generate_stat.start_date:
        # start_date = '2024-10-01'
        generate_stat.start_date = datetime.today().strftime('%Y-%m-%d')
    current_date = datetime.strptime(generate_stat.start_date, '%Y-%m-%d')
    end_date = datetime.today()
    # 从start_date开始逐步统计到今天
    while current_date <= end_date:
        current_date_str = current_date.strftime('%Y-%m-%d')
        result = await SettlementService.generate_stat_stock_services(query_db, current_date_str)
        current_date += timedelta(days=1)
        logger.info(f'生成{current_date_str}统计数据成功: {result.message}')
    return ResponseUtil.success(msg="股票统计完成")


@settlementController.get('/stat_settlement_list')
async def get_stat_settlement_list(
        request: Request,
        stock_code: str,
        account_tag: str,
        query_db: AsyncSession = Depends(get_db),
):
    """
    根据证券代码和账户标签获取交易明细

    :param request: 请求对象
    :param stock_code: 证券代码
    :param account_tag: 账户标签
    :param query_db: 数据库会话
    :return: 交易明细列表
    """
    logger.info('获取成功')

    result = await SettlementService.get_stock_settlement_list(query_db, stock_code, account_tag)
    return ResponseUtil.success(rows=result)
